package com.jiuyue.redis.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.jiuyue.redis.entity.User;
import com.jiuyue.redis.service.UserService;

@RestController
public class RedisController {
	
	   @Autowired
	    private RedisTemplate<String,String> redisTemplate;
	    @Autowired
	    private UserService userService;
	 
	    public static final String SCORE_RANK = "score_rank";
	 
	    @GetMapping("/hello")
	    public String hello(){
	        Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();
	        List<User> users = userService.selectUserListAll();
	        if(CollectionUtils.isNotEmpty(users)){
	            for (User user:users) {
	                DefaultTypedTuple<String> tuple = new DefaultTypedTuple<>(user.getName(), user.getScore());
	                tuples.add(tuple);
	            }
	        }
	        Long num = redisTemplate.opsForZSet().add(SCORE_RANK, tuples);
	        Set<ZSetOperations.TypedTuple<String>> rangeWithScores = redisTemplate.opsForZSet().reverseRangeWithScores(SCORE_RANK, 0, 10);
	        System.out.println("获取到的排行和分数列表:" + JSON.toJSONString(rangeWithScores));
	        return JSON.toJSONString(rangeWithScores);
	    }

}
